package net.hhk.twitter;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import net.hhk.connect.HTTPConnect;
import net.hhk.controller.TweetAdapter;
import net.hhk.controller.TweetManager;
import net.hhk.controller.UserAdapter;
import net.hhk.controller.UserManager;
import net.hhk.data.Constant;
import net.hhk.data.MySharePreferences;
import net.hhk.data.Tweet;
import net.hhk.data.User;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class UserFollowActivity extends ListActivity {

	private UserManager mgr;
	private UserAdapter mAdapter;
	private Boolean isFollowing;
	private String newFollowUser = "";
	private String newUnFollow = "";
	private int id;
	private View mLoadMoreFooter;

	private boolean mLoading;

	private static final int MSG_APPEND_MORE_ITEMS = 0;

	private static final int NUMBER_OF_ITEMS_REQUESTED = 8;
	private int currentPage = 1;
	private MySharePreferences sharePre;
	private int myid = 0;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle b = getIntent().getExtras();
		isFollowing = b.getBoolean("isfollowing");
		id = b.getInt("id");
		setContentView(R.layout.list_following_layout);

		sharePre = (MySharePreferences) getApplicationContext();
		myid = sharePre.getExitInt("myid", 0);

		mgr = new UserManager(getApplicationContext(), isFollowing);

		TextView follow_title = (TextView) findViewById(R.id.follow_title);
		follow_title.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(getApplicationContext(),
						MainActivity.class);
				i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				startActivity(i);
				finish();

			}
		});
		if (isFollowing)
			follow_title.setText("Following");
		else
			follow_title.setText("Followers");

		LinearLayout write_tweet = (LinearLayout) findViewById(R.id.home_write_tweet);
		write_tweet.setOnClickListener(clickWriteTweet);

		Button btn = (Button) findViewById(R.id.btn_tweet);
		btn.setOnClickListener(clickWriteTweet);
		
		LinearLayout searchLayout = (LinearLayout) findViewById(R.id.btnSearch_layout);
		searchLayout.setOnClickListener(clickSearch);
		Button btnSearch = (Button) findViewById(R.id.btn_search);
		btnSearch.setOnClickListener(clickSearch);

		LayoutInflater inflater = LayoutInflater.from(this);
		mLoadMoreFooter = inflater.inflate(R.layout.profile, null);

		getListView().addFooterView(mLoadMoreFooter);
		getListView().setOnScrollListener(mScrollListener);

		mLoading = false;
		// mAdapter = new UserAdapter(this, mgr.getSocialFeed(Constant.TIMELINE,
		// 0, 1, NUMBER_OF_ITEMS_REQUESTED));
		// mAdapter = new UserAdapter(this, getUser());
		// setListAdapter(mAdapter);
		loadData();
		ListView list = getListView();

		// list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
	}
	private OnClickListener clickSearch = new OnClickListener() {

		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent i = new Intent(getApplicationContext(), SearchActivity.class);

			startActivity(i);

		}
	};

	private OnClickListener clickWriteTweet = new OnClickListener() {

		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent i = new Intent(getApplicationContext(),
					WriteTweetActivity.class);
			Bundle b = new Bundle();

			b.putInt("isReply", 0);
			i.putExtras(b);
			startActivity(i);

		}
	};

	private void loadMoreItems() {
		mLoading = true;
		new Thread() {
			public void run() {
				try {
					// in this example, we just simply wait for 2 seconds
					Thread.sleep(2000);
					Message msg = mMainhandler.obtainMessage(
							MSG_APPEND_MORE_ITEMS, generateList());
					mMainhandler.sendMessage(msg);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			};
		}.start();
	}

	private Handler mMainhandler = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_APPEND_MORE_ITEMS:
				ArrayList newData = (ArrayList) msg.obj;
				if (mAdapter == null) {
					mAdapter = new UserAdapter(UserFollowActivity.this,
							newData, myid);
					setListAdapter(mAdapter);
				} else {

					mAdapter.appendItems(newData);
				}

				if (newData.size() < NUMBER_OF_ITEMS_REQUESTED) {
					getListView().removeFooterView(mLoadMoreFooter);

					mLoading = false;
					break;
				}
			}

		}
	};

	private ArrayList generateList() {
		currentPage++;

		return (ArrayList<User>) getUser();
	}

	private void checkLoadMore() {

		if (mLoading)
			return;

		/*
		 * if the loading footer is still there, then we will load more items
		 */
		if (getListView().getFooterViewsCount() != 0) {
			loadMoreItems();
		}
	}

	private OnScrollListener mScrollListener = new OnScrollListener() {

		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// We have nothing to do with this right now
		}

		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			// minus 1 here because the total list item count include the
			// loading footer
			if (view.getLastVisiblePosition() >= 0) {
				if (view.getLastVisiblePosition() >= (totalItemCount - 1)) {
					mLoading = false;
					checkLoadMore();
				}
			}
		}
	};

	public void onBackPressed() {
		super.onBackPressed();
		// Intent setIntent = new Intent(getApplicationContext(),
		// ViewProfileActivity.class);
		//
		// startActivity(setIntent);
		finish();

		return;
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);
		User user = (User) l.getItemAtPosition(position);
		int userid = user.getUserid();
		Intent i = new Intent(getApplicationContext(),
				UserProfileActivity.class);
		Bundle b = new Bundle();
		b.putInt("id", userid);
		i.putExtras(b); // Put your id to your next Inten
		startActivity(i);
	}

	public List<User> getUser() {
		if (id > 0) {
			if (isFollowing)
				return mgr.getSocialFeed(Constant.GET_USER_FOLLOWING, id,
						currentPage, NUMBER_OF_ITEMS_REQUESTED);
			else
				return mgr.getSocialFeed(Constant.GET_USER_FOLLOWER, id,
						currentPage, NUMBER_OF_ITEMS_REQUESTED);
		} else {
			if (isFollowing)
				return mgr.getSocialFeed(Constant.GET_FOLLOWING, id,
						currentPage, NUMBER_OF_ITEMS_REQUESTED);
			else
				return mgr.getSocialFeed(Constant.GET_FOLLOWER, id,
						currentPage, NUMBER_OF_ITEMS_REQUESTED);
		}

	}

	private void loadData() {
		AsyncTask<String, Void, List<User>> asyncTask = new AsyncTask<String, Void, List<User>>() {

			/*
			 * (non-Javadoc)
			 * 
			 * @see android.os.AsyncTask#onPreExecute()
			 */
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
			}

			@Override
			protected List<User> doInBackground(String... params) {
				// Following actions will be done in background
				if (id > 0) {
					if (isFollowing)
						return mgr.getSocialFeed(Constant.GET_USER_FOLLOWING,
								id, currentPage, NUMBER_OF_ITEMS_REQUESTED);
					else
						return mgr.getSocialFeed(Constant.GET_USER_FOLLOWER,
								id, currentPage, NUMBER_OF_ITEMS_REQUESTED);
				} else {
					if (isFollowing)
						return mgr.getSocialFeed(Constant.GET_FOLLOWING, id,
								currentPage, NUMBER_OF_ITEMS_REQUESTED);
					else
						return mgr.getSocialFeed(Constant.GET_FOLLOWER, id,
								currentPage, NUMBER_OF_ITEMS_REQUESTED);

				}

			}

			/*
			 * (non-Javadoc)
			 * 
			 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
			 */
			@Override
			protected void onPostExecute(List<User> result) {
				super.onPostExecute(result);
				mAdapter = new UserAdapter(UserFollowActivity.this, result,
						myid);

				setListAdapter(mAdapter);
				if (mAdapter.getCount() < NUMBER_OF_ITEMS_REQUESTED) {
					if (getListView().getFooterViewsCount() > 0)
						getListView().removeFooterView(mLoadMoreFooter);
					mLoading = false;
				}

			}
		};
		asyncTask.execute("Saurabh");
	}

	protected void onPause() {
		super.onPause();
		getListUserChange();
		// mAdapter.clearCache();

	}

	public void getListUserChange() {
		// List<User> users = mgr.getUsers();
		for (int i = 0; i < (getListView().getCount()
				- getListView().getFooterViewsCount() - getListView()
				.getHeaderViewsCount()); i++) {
			User user = (User) getListView().getItemAtPosition(i);
			if (user.isIsfollowed()) {
				if (!user.isLastStatus())
					newUnFollow = newUnFollow
							+ Integer.toString(user.getUserid()) + ";";
			} else {
				if (user.isLastStatus())
					newFollowUser = newFollowUser
							+ Integer.toString(user.getUserid()) + ";";
			}

		}
		if (newUnFollow.length() > 0)
			newUnFollow = newUnFollow.substring(0, newUnFollow.length() - 1);
		if (newFollowUser.length() > 0)
			newFollowUser = newFollowUser.substring(0,
					newFollowUser.length() - 1);
		List<NameValuePair> postParameters = new ArrayList<NameValuePair>();

		postParameters
				.add(new BasicNameValuePair("userid_array", newFollowUser));

		HTTPConnect http = HTTPConnect.getConnect();
		String result = http.doConnect(Constant.SET_FOLLOW, postParameters);

		postParameters = new ArrayList<NameValuePair>();

		postParameters.add(new BasicNameValuePair("userid_array", newUnFollow));

		String result2 = http.doConnect(Constant.SET_UN_FOLLOW, postParameters);
	}

}